package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import adapters.OrdersManageAdapter;
import mytools.DoubleDatePickerDialog;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.OC_YZJH_Detail;
import service.WebService;

public class OrdersManageActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, AdapterView.OnItemLongClickListener {

    private TextView om_dateStart;
    private TextView om_dateEnd;
    private LinearLayout om_dateLinear;
    private SwipeRefreshLayout mSwipeLayout;
    private ListView mListView;
    private OrdersManageAdapter mAdapter;
    private String mYZJHResult;
    private static ProgressDialog progressDialog = null;

    private List<OC_YZJH_Detail> mYZJHList;
    private String ZYH;
    private String startDate, endDate;
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_manage);

        onBindUI();
        setNeedsMenuKey();
        mSwipeLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        mSwipeLayout.setOnRefreshListener(this);
        om_dateLinear.setOnClickListener(this);

        mAdapter = new OrdersManageAdapter(this);

        mListView.setAdapter(mAdapter);

        mListView.setOnItemLongClickListener(this);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.om_select_all:
                    boolean isSelectALL = !mAdapter.isSelectAll();
                    mAdapter.selectAll(isSelectALL);
                    mAdapter.notifyDataSetChanged();
                    String title = isSelectALL ? "全不选" : "全选";
                    item.setTitle(title);
                    break;
                case R.id.om_cancel:
                    break;
                case R.id.om_deny:
                    break;
            }
            return false;
        });

    }

    private void onBindUI() {
        om_dateLinear = findViewById(R.id.order_manage_top_linear);
        om_dateStart = findViewById(R.id.om_date_start);
        om_dateEnd = findViewById(R.id.om_date_end);
        mSwipeLayout = findViewById(R.id.om_swipe);
        mListView = findViewById(R.id.om_listview);
        bottomNavigationView = findViewById(R.id.om_bottom);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Date date = new Date();
        String dateString = sdf.format(date);
        startDate = dateString;
        endDate = dateString;
        om_dateStart.setText(startDate);
        om_dateEnd.setText(endDate);
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            ZYH = inPatient.getZYH();
            if (ZYH != null) {
                doFlushData(false);
            }
        }
    }

    @Override
    public void onRefresh() {
        doFlushData(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
//            case KeyEvent.KEYCODE_MENU:
//                if (bottomNavigationView != null) {
//                    int VISIBILITY = bottomNavigationView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
//                    bottomNavigationView.setVisibility(VISIBILITY);
//                }
//                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        Calendar calendarS = Calendar.getInstance();
        Calendar calendarE = Calendar.getInstance();
        try {
            Date date_S = sdf.parse(startDate);
            Date date_E = sdf.parse(endDate);
            calendarS.setTime(date_S);
            calendarE.setTime(date_E);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        new DoubleDatePickerDialog(OrdersManageActivity.this, 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth, endDatePicker, endYear, endMonthOfYear, endDayOfMonth) -> {
            String date_Start = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
            String date_End = endYear + "-" + (endMonthOfYear + 1) + "-" + endDayOfMonth;
            if (date_Start.compareTo(date_End) > 0) {
                Toast.makeText(OrdersManageActivity.this, "开始日期不能大于结束日期！", Toast.LENGTH_SHORT).show();
            } else {
                om_dateStart.setText(date_Start);
                om_dateEnd.setText(date_End);
                startDate = date_Start;
                endDate = date_End;
                showProgressBar(OrdersManageActivity.this);
                new MyGetYZJHTask().execute(ZYH, startDate, endDate);
            }
        }, calendarS.get(Calendar.YEAR), calendarS.get(Calendar.MONTH), calendarS.get(Calendar.DATE), calendarE.get(Calendar.YEAR), calendarE.get(Calendar.MONTH), calendarE.get(Calendar.DATE),
                false).show();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showChooseDialog(this);
        return false;
    }


    /**
     * 获取医嘱计划
     */
    private class MyGetYZJHTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getYZJHWebService = new WebService(OrdersManageActivity.this);
            getYZJHWebService.setMETHOD_NAME("getYZJHResult");
            String result;
            getYZJHWebService.setPARMS(parms);
            result = getYZJHWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取医嘱计划列表为空！";
            } else {
                if (!result.equals(mYZJHResult)) {
                    mYZJHResult = result;
                    Gson gson = new Gson();
                    mYZJHList = gson.fromJson(mYZJHResult, new TypeToken<List<OC_YZJH_Detail>>() {
                    }.getType());
                    if (mYZJHList != null && mYZJHList.size() > 0) {
                        return null;
                    } else {
                        return "获取医嘱计划列表失败!";
                    }
                } else {
                    return "医嘱计划数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (mSwipeLayout.isRefreshing()) {
                mSwipeLayout.setRefreshing(false);
            }
            if (s != null) {
                Toast.makeText(OrdersManageActivity.this, s, Toast.LENGTH_SHORT).show();
            } else {
                mAdapter.setmOMList(mYZJHList);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    private void doFlushData(boolean isSwipe) {
        if (!isSwipe) {
            showProgressBar(this);
        }
        String[] parms = {ZYH, startDate, endDate};
        new MyGetYZJHTask().execute(parms);
    }

    //显示虚拟菜单按钮
    private void setNeedsMenuKey() {
        try {
            Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class);
            setNeedsMenuKey.setAccessible(true);
            int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null);
            setNeedsMenuKey.invoke(getWindow(), value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showChooseDialog(final Context context) {
        final String[] items = new String[]{"计划拒绝", "计划取消"};
        AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(context);
        mChooseDialogBuilder.setTitle("计划操作");
        mChooseDialogBuilder.setItems(items, (dialog, which) -> {
            switch (which) {
                case 0:
                    showWarnDialog("是否要拒绝该医嘱计划？", "计划已拒绝");
                    dialog.dismiss();
                    break;
                case 1:
                    showWarnDialog("是否要取消该医嘱计划？", "计划已取消");
                    dialog.dismiss();
                    break;
            }
        }).show();
    }

    private void showWarnDialog(String msg1, final String msg2) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrdersManageActivity.this);
        builder.setMessage(msg1);
        builder.setTitle("提示");
        builder.setPositiveButton("确认", (dialog, which) -> {
            Toast.makeText(OrdersManageActivity.this, msg2, Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

}
